<?php

namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class IdentityCardRule implements Rule
{
    public $message;

    /**
     * Create a new rule instance.
     *
     */
    public function __construct()
    {
        $this->message = '';
    }

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $card_number = strval($value);
        if (strlen($card_number) !== 18) {
            $this->message = '身份账号码必须18位';
            return false;
        }

        $coefficient = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        $verify_arr = [1, 0, 'x', 9, 8, 7, 6, 5, 4, 3, 2];

        $sum = 0;
        for ($i = 0; $i <= strlen($card_number) - 2; $i++) {
            $sum += $card_number[$i] * $coefficient[$i];
        }

        $verify = $sum % 11;

        if ($verify < 0 || $verify > 10) {
            $this->message = '身份证号码错误';
            return false;
        }

        if ($verify_arr[$verify] != strtolower($card_number[17])) {
            $this->message = '身份证号码错误';
            return false;
        }

        return true;
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        return $this->message;
    }
}
